import axios from 'axios'
import { clearToken, getToken } from './token'
import { message } from 'antd'
import { history as customHistory } from '@/router/history'

const baseURL = process.env.REACT_APP_URL

const request = axios.create({
  baseURL,
  timeout: 5000
})


// 请求拦截器
request.interceptors.request.use(config => {
  // 获取token
  const token = getToken()

  // 除登录请求外,其余请求统一加上token
  if (!config.url.startsWith('/authorizations')) {
    config.headers.Authorization = `Bearer ${token}`
  }

  return config

}, err => {
  return Promise.reject(err)
})

// 响应拦截器
request.interceptors.response.use((config) => { return config }, err => {
  if (!err.response) {
    message.error('网络繁忙,请稍后重试!')
    return Promise.reject(err)
  }

  if (err.response.status === 401) {
    message.error(err.response.data?.message, 1.5, () => {
      // 删除token
      clearToken()
      customHistory.push('/login', {
        from: customHistory.location.pathname
      })
    })
  }

  return Promise.reject(err)
})

export default request